//
//  GChatViewController.m
//  SouthChina
//  群聊主页面
//  Created by zorro on 15/6/22.
//  Copyright (c) 2015年 科创. All rights reserved.
//

#import "GChatViewController.h"
#import "SYTabBar.h"
#import "SYTabBarItem.h"
#import "MessageSessionDao.h"
#import "MessageSession.h"
#import "Contact.h"
#import "ContactDao.h"
#import "MessageSessionCell.h"
#import "FriendVerifyViewController.h"
#import "GroupTableViewCell.h"
#import "SDRefresh.h"
#import "GroupInfoViewController.h"
#import "CreateGroupViewController.h"
#import "selectMemberViewController.h"
#import "PersonalCenterTableViewCell.h"
#import "SearchGroupViewController.h"
#import "ZbarReaderViewController.h"

@interface GChatViewController ()<SYTabBarDelegate,UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>
{
    NSMutableArray * groupData;         //我的群数据
    NSMutableArray * organizationData;  //组织机构群数据
    NSMutableArray * interestData;      //兴趣群数据
    SDRefreshFooterView *refreshOrganizationFooterView;   //组织机构列表刷新
    SDRefreshFooterView *refreshInterestPageNoFooterView; //兴趣群列表刷新
    NSInteger  organizationPageNo;      //当前查询的组织机构群页数
    NSInteger  interestPageNo;          //当前查询的兴趣群页数
    int pageSize;                       //每次翻页数量
    NSMutableArray * chatData;          //我的讨论组
   // NSArray *sTitls;
   // NSArray *sPics;
}
@end

@implementation GChatViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    organizationPageNo = 1;
    interestPageNo = 1;
    pageSize = 10;
    
    groupData = [[NSMutableArray alloc]init];
    organizationData = [[NSMutableArray alloc]init];
    interestData = [[NSMutableArray alloc]init];
    chatData = [[NSMutableArray alloc]init];
    if([_GChatType isEqualToString:@"5"])
       [self addTitleBarWithBackBtn:@"群聊" needReturn:YES];
    else
         [self addTitleBarWithBackBtn:@"讨论组" needReturn:YES];
    
    UIView * bodyView = [[[NSBundle mainBundle] loadNibNamed:@"GroupChatView" owner:self options:nil] objectAtIndex:0];
    bodyView.frame = (CGRect){0, self.titlebar.frame.origin.y+self.titlebar.frame.size.height,  SCREEN_WIDTH, SCREEN_HEIGHT-self.titlebar.frame.size.height};
    [self.view addSubview:bodyView];
    
    //导航栏上面的+号按钮
     UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
     rightBtn.frame = CGRectMake(270.0f, (YNEW)+5, 40.0f, 30.0f);
     [rightBtn addTarget:self action:@selector(showRightBtnView:) forControlEvents:UIControlEventTouchUpInside];
     [rightBtn setImage:[UIImage imageNamed:@"addfriend_group_flag"] forState:UIControlStateNormal];
     rightBtn.imageEdgeInsets = UIEdgeInsetsMake ( 5 ,  10 , 5 , 10 );
     
     [self.titlebar addSubview:rightBtn];
    
    //sTitls = @[@"创建群组",@"创建讨论组",@"扫一扫进群"];
    //sPics = @[@"creategroup.png",@"creategroup.png",@"pic_scan"];
    
    //搜素框
    _searchGroup.showsCancelButton=NO;
    _searchGroup.barStyle=UIBarStyleDefault;
    _searchGroup.placeholder = @"";
    _searchGroup.delegate =self;
    
    //如果是讨论组，此处隐藏选择tabbar
    if([_GChatType isEqualToString:@"4"])
    {
        _tabBarHeight.constant = 0.1;
        _tabGroup.delegate = self;
        _tabGroup.dataSource = self;
        _tabGroup.tag = GCHATTYPE_CHAT;
        _tabGroup.backgroundColor =[UIColor whiteColor];
        [self refreshChatTableView];
    }
    else
    {
        NSMutableArray *tabBarItmes = [[NSMutableArray alloc] initWithCapacity:3];
        NSString * arrTitles[3] = {@"我的群",@"行政群",@"兴趣群"};
        for (int i = 0; i < 3; i ++)
        {
            SYTabBarItem *itemTempA = [[SYTabBarItem alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH / 3.0, 44 ) title:arrTitles[i] selectedImage:nil unselectedImage:nil];
            itemTempA.selectedTitleColor = BASIC_BLUE_COLOR;
            [itemTempA setTitleFont:[UIFont systemFontOfSize:15.0f]];
            itemTempA.unselectedTitleColor = [UIColor colorWithRed:111.0f/255.0f green:111.0f/255.0f blue:111.0f/255.0f alpha:1.0f];

            [tabBarItmes addObject:itemTempA];
        }

        //initalize the tab barA
        _SelectGroup = [_SelectGroup initWithSYTabBarItems:tabBarItmes];
        _SelectGroup.tabBarDelegate = self;
        [_SelectGroup setShowDividingLine:NO];


        [_SelectGroup selectItemAtIndex:0];
        
        _tabGroup.delegate = self;
        _tabGroup.dataSource = self;
        _tabGroup.tag = GCHATTYPE_MY;
        _tabGroup.backgroundColor =[UIColor whiteColor];
        _tabOrganization.delegate = self;
        _tabOrganization.dataSource = self;
        _tabOrganization.tag = GCHATTYPE_ORGANIZATION;
        _tabOrganization.backgroundColor =[UIColor whiteColor];
        _tabInterest.delegate = self;
        _tabInterest.dataSource = self;
        _tabInterest.tag = GCHATTYPE_INTEREST;
        _tabInterest.backgroundColor =[UIColor whiteColor];
        
        [self refreshTableView];
        [self setupHeader];
    }
}


- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    //跳转到通讯录通用搜索页面
    SearchGroupViewController * searchgroup =[[SearchGroupViewController alloc] initWithNibName:nil bundle:nil];
    [kAppDelegate.iCSDrawerController.navigationController pushViewController:searchgroup animated:YES];
    return  NO;//返回NO不显示键盘
}

-(void)showRightBtnView:(id)sender
{
    CGFloat xWidth = self.view.bounds.size.width - 162.0f;
    CGFloat yHeight = 40.0f;
    UIPopoverListView *poplistview = [[UIPopoverListView alloc] initWithFrame:CGRectMake(0, 0, xWidth, yHeight)];
    poplistview.delegate = self;
    poplistview.datasource = self;
    poplistview.listView.scrollEnabled = YES;
    poplistview.center = CGPointMake(240,86);
    [poplistview show];
    
}

#pragma mark - UIPopoverListViewDataSource

- (UITableViewCell *)popoverListView:(UIPopoverListView *)popoverListView
                    cellForIndexPath:(NSIndexPath *)indexPath
{
   static NSString * CellIdentifier = @"PersonalCenterTableViewCell";
   PersonalCenterTableViewCell *cell = [[PersonalCenterTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
    
    UIImageView *cellimage =  [[UIImageView alloc] initWithFrame:CGRectMake(15, 10,25, 20)];
    UILabel * titlaLabel = [[UILabel alloc] initWithFrame:CGRectMake(45, 10, 100, 20)];
   // titlaLabel.text = sTitls[indexPath.row];
    //cellimage.image = [UIImage imageNamed:sPics[indexPath.row]];
    titlaLabel.text = @"123";
    cellimage.image = [UIImage imageNamed:@"chat.png"];
    [cell addSubview:cellimage];
    
    titlaLabel.textColor = [UIColor colorWithRed:85.0f/255.0f green:85.0f/255.0f blue:85.0f/255.0f alpha:1.0f];
    titlaLabel.textAlignment = NSTextAlignmentLeft;
    titlaLabel.font = [UIFont boldSystemFontOfSize:14.0f];
    [cell addSubview:titlaLabel];
    
    return cell;
}

- (NSInteger)popoverListView:(UIPopoverListView *)popoverListView
       numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

#pragma mark - UIPopoverListViewDelegate
- (void)popoverListView:(UIPopoverListView *)popoverListView
     didSelectIndexPath:(NSIndexPath *)indexPath
{
   /* if(indexPath.row==0)
    {
        CreateGroupViewController * groupCreate = [[CreateGroupViewController alloc] init];
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:groupCreate animated:NO];
    }
    else if(indexPath.row == 1)
    {
        selectMemberViewController * chatCreate = [[selectMemberViewController alloc] init];
        NSMutableSet *selectedContact = [[NSMutableSet alloc]init];
        chatCreate.selectedContact = selectedContact;
        chatCreate.CreateType =CREATETYPE_CREATECHAT;
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:chatCreate animated:NO];
    }
    else if(indexPath.row == 2) //扫一扫
    {
        ZbarReaderViewController * scanning = [[ZbarReaderViewController alloc] init];
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:scanning animated:NO];
    }*/
    
}

- (CGFloat)popoverListView:(UIPopoverListView *)popoverListView
   heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50.0f;
}


- (void)setupHeader
{
    refreshOrganizationFooterView = [SDRefreshFooterView refreshView];
    
    [refreshOrganizationFooterView addToScrollView:_tabOrganization];
    
    [refreshOrganizationFooterView addTarget:self refreshAction:@selector(OrganizationfooterRefresh)];
    
    refreshInterestPageNoFooterView = [SDRefreshFooterView refreshView];
    
    [refreshInterestPageNoFooterView addToScrollView:_tabInterest];
    
    [refreshInterestPageNoFooterView addTarget:self refreshAction:@selector(InterestfooterRefresh)];
    
}
- (void)dealloc
{
    [refreshOrganizationFooterView removeFromSuperview];
    [refreshInterestPageNoFooterView removeFromSuperview];
}

- (void)OrganizationfooterRefresh
{
    [self refreshGChatTableView:_tabOrganization arrayData:organizationData key:@"" pageNo:&organizationPageNo FooterView:refreshOrganizationFooterView];
    
}

- (void)InterestfooterRefresh
{
    [self refreshGChatTableView:_tabInterest arrayData:interestData key:@"" pageNo:&interestPageNo  FooterView:refreshInterestPageNoFooterView];
}

-(void) refreshGChatTableView:(UITableView *)tab arrayData:(NSMutableArray *)arrayData key:(NSString*) key pageNo:(NSInteger*) pageNo  FooterView:(SDRefreshFooterView*)footerView
{
    NSDictionary *map = @{@"groupType":_GChatType,@"groupName":key,@"pageNo": [NSString stringWithFormat:@"%ld",(long)*pageNo],@"pageSize":[NSString stringWithFormat:@"%d",pageSize]};
    
    //如果上次现实加载提示窗还没清除，又进行了调用，界面出现多个提示框，清理时会出异常，导致无法全部清理干净，界面僵死
    
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [DE serverCall:@"searchGrp" params:map callback:^(BOOL success, int code, NSString *desc, NSDictionary *data,NSDictionary*param) {
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if(success)
        {
            NSArray *array =  [data objectForKey:@"grps"];
            if([array count] >0)
            {
                (*pageNo)++;
                [arrayData addObjectsFromArray:array];
                [tab reloadData];
            }
        }
        else{
            [self showAlerHUD:@"获取群列表失败"];
        }

        [footerView endRefreshing];
    }];
}

-(void) refreshTableView
{
    NSMutableArray *array  = [[NSMutableArray alloc] initWithArray:[ContactDao getContactByWhere:@"where org_type='Group' and operate='U'"]];
    
    NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@"mHAS_CHILD== %@", @"1"];
    NSArray *MyAPP = [array filteredArrayUsingPredicate:predicate1];
    
    NSPredicate *predicate2 = [NSPredicate predicateWithFormat:@"mHAS_CHILD== %@", @"0"];
    NSArray *NoMyAPP = [array filteredArrayUsingPredicate:predicate2];

    groupData = [[NSMutableArray alloc]init];
    if(MyAPP != nil && MyAPP.count != 0)
    {
        [groupData addObject:[NSDictionary dictionaryWithObjectsAndKeys:@"我管理的群",@"name",MyAPP,@"group", nil]];
    }
    
    if (NoMyAPP != nil && NoMyAPP.count != 0)
    {
        [groupData addObject:[NSDictionary dictionaryWithObjectsAndKeys:@"我加入的群",@"name",NoMyAPP,@"group", nil]];
    }    
    
    [_tabGroup reloadData];
}

-(void) refreshChatTableView
{
    chatData  = [[NSMutableArray alloc] initWithArray:[ContactDao getContactByWhere:@"where org_type='Chat' and operate='U' "]];
    
    [_tabGroup reloadData];
}

//列表组
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if(tableView.tag == GCHATTYPE_MY)
    {
        return groupData.count;
    }
    
    return 1;
}

//指定标题的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(tableView.tag == GCHATTYPE_MY)
        return 25;
    return 0.1;
}

//指定标题的高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}


- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"置顶聊天";
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        //设置当前群为置顶群
        //Contact * groupContact = [groupData objectAtIndex:indexPath.row];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(tableView.tag == GCHATTYPE_MY)
        return  [[[groupData objectAtIndex:section] objectForKey:@"group"] count];
    else if (tableView.tag == GCHATTYPE_ORGANIZATION)
        return organizationData.count;
    else if (tableView.tag == GCHATTYPE_INTEREST)
        return interestData.count;
    else if (tableView.tag == GCHATTYPE_CHAT)
        return chatData.count;
    return 0;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
  
    if(tableView.tag == GCHATTYPE_MY)
     return   [[groupData objectAtIndex:section] objectForKey:@"name"];

    return @"";
}

-(void) tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
    if ([view isKindOfClass: [UITableViewHeaderFooterView class]]) {
        UITableViewHeaderFooterView* castView = (UITableViewHeaderFooterView*) view;
        
        castView.contentView.backgroundColor = [UIColor colorWithWhite:0.875 alpha:1.000];
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString * CellIdentifier = @"GroupTableViewCell";
    GroupTableViewCell * cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:CellIdentifier];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil] objectAtIndex:0];
         cell.imgtopstraint.constant = 7;
         cell.imgbotmstraint.constant = 7;
         cell.imgHead.layer.masksToBounds = YES;
         cell.imgHead.layer.cornerRadius = 16;
    }

    if(tableView.tag == GCHATTYPE_MY)
    {
        Contact *group  =  [[[groupData objectAtIndex:indexPath.section] objectForKey:@"group"] objectAtIndex:indexPath.row];
        cell.labTitle.text = group.mNAME;
        
        NSURL *url= [NSURL URLWithString: [group.mHEAD_IMG hasPrefix:@"http"]?group.mHEAD_IMG:[NSString stringWithFormat:@"%@%@",DE.fileEngineeUrl,group.mHEAD_IMG]];
        [cell.imgHead setImageWithURL:url placeholderImage:[UIImage imageNamed:@"group"]];
    }
    else if (tableView.tag == GCHATTYPE_ORGANIZATION)
    {
        cell.labTitle.text = [[organizationData objectAtIndex:indexPath.row] objectForKey:@"groupName" ];
        NSString *sHeadImg = [[organizationData objectAtIndex:indexPath.row] objectForKey:@"headImg" ];
        NSURL *url= [NSURL URLWithString: [sHeadImg hasPrefix:@"http"]?sHeadImg:[NSString stringWithFormat:@"%@%@",DE.fileEngineeUrl,sHeadImg]];
        
        [cell.imgHead setImageWithURL:url placeholderImage:[UIImage imageNamed:@"group"]];
    }
    else if (tableView.tag == GCHATTYPE_INTEREST)
    {
        cell.labTitle.text = [[interestData objectAtIndex:indexPath.row] objectForKey:@"groupName" ];
        NSString *sHeadImg = [[interestData objectAtIndex:indexPath.row] objectForKey:@"headImg" ];
        NSURL *url= [NSURL URLWithString: [sHeadImg hasPrefix:@"http"]?sHeadImg:[NSString stringWithFormat:@"%@%@",DE.fileEngineeUrl,sHeadImg]];
        
        [cell.imgHead setImageWithURL:url placeholderImage:[UIImage imageNamed:@"group"]];
    }
    else if (tableView.tag == GCHATTYPE_CHAT)
    {
        Contact *group  =  [chatData objectAtIndex:indexPath.row];
        cell.labTitle.text = group.mNAME;
        
        NSURL *url = [NSURL URLWithString:group.mHEAD_IMG];
        [cell.imgHead setImageWithURL:url placeholderImage:[UIImage imageNamed:@"chat"]];
    }


    return  cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 65;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if(tableView.tag == GCHATTYPE_MY)
    {
        Contact *group =  [[[groupData objectAtIndex:indexPath.section] objectForKey:@"group"]  objectAtIndex:indexPath.row];
        MessageViewController * message = [[MessageViewController alloc]init];
        NSDictionary *dicc = @{@"sessionType":MESSAGE_TYPE_P2G,@"messtype":@"1",@"record_DB_ID":group.mPK_ID,
                               @"recordID":group.mID};
        message.sessInfo = dicc;
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:message animated:NO];
        return;
    }
    if(tableView.tag == GCHATTYPE_CHAT)
    {
        NSLog(@"讨论组");
        Contact *group =  [chatData  objectAtIndex:indexPath.row];
        MessageViewController * message = [[MessageViewController alloc]init];
        NSDictionary *dicc = @{@"sessionType":MESSAGE_TYPE_P2G,@"messtype":@"1",@"record_DB_ID":group.mPK_ID,
                               @"recordID":group.mID};
        message.sessInfo = dicc;
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:message animated:NO];
        return;
    }
    else if (tableView.tag == GCHATTYPE_ORGANIZATION)//行政群
    {
        ///测试
        NSArray *keys;
        int i, count;
        id key, value;
        
        keys = [[ organizationData objectAtIndex:indexPath.row] allKeys];
        count = [keys count];
        for (i = 0; i < count; i++)
        {
            key = [keys objectAtIndex: i];
            value = [[ organizationData objectAtIndex:indexPath.row] objectForKey: key];
            NSLog (@"Key: %@ for value: %@", key, value);
        }
        ///
        
        //群信息设置
         NSLog(@"群名称：%@,群id:%@",[[ organizationData objectAtIndex:indexPath.row] objectForKey:@"groupName" ],[[ organizationData objectAtIndex:indexPath.row] objectForKey:@"groupId" ]);
        GroupInfoViewController *group = [[GroupInfoViewController alloc]init];
        group.groupid = [[organizationData objectAtIndex:indexPath.row] objectForKey:@"groupId" ];
        group.grouptype= TYPE_GROUP_ORGANIZATION;
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:group animated:NO];
        
    }
    else if(tableView.tag== GCHATTYPE_INTEREST)//兴趣群
    {
        //群信息设置
        GroupInfoViewController *group = [[GroupInfoViewController alloc]init];
        group.groupid = [[ interestData objectAtIndex:indexPath.row] objectForKey:@"groupId" ];
        group.grouptype= TYPE_GROUP_INTEREST;
        NSLog(@"群名称：%@,群id:%@",[[ interestData objectAtIndex:indexPath.row] objectForKey:@"groupName" ],[[ interestData objectAtIndex:indexPath.row] objectForKey:@"groupId" ]);
        
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:group animated:NO];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)tabBar:(SYTabBar *)tabBar didSelectItem:(SYTabBarItem *)item
{
    [item setBackgroundImage:[UIImage imageNamed:@"button_line2"]];
    if(item.tag == 0)
    {
        //显示我的群
        //searchGrp
        _tabGroup.hidden  =FALSE;
        _tabInterest.hidden = TRUE;
        _tabOrganization.hidden = TRUE;
        _GChatType =@"1";
    }
    else if(item.tag == 1)
    {
        //查询组织机构群
        _tabGroup.hidden  =TRUE;
        _tabInterest.hidden = TRUE;
        _tabOrganization.hidden = FALSE;
        _GChatType =@"2";
        
        if(organizationPageNo ==1)
            [self refreshGChatTableView:_tabOrganization arrayData:organizationData key:@"" pageNo:&organizationPageNo FooterView:nil];
    }
    else if(item.tag == 2)
    {
        //查询普通群
        _tabGroup.hidden  =TRUE;
        _tabInterest.hidden = FALSE;
        _tabOrganization.hidden = TRUE;
        _GChatType =@"3";
        
        if(interestPageNo ==1)
        [self refreshGChatTableView:_tabInterest arrayData:interestData key:@"" pageNo:&interestPageNo FooterView:nil];
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

//返回上一级页面（这里重写btnBack 目的是为了刷新通讯录中tabbar索引）
- (void)btnBack {
    kAppDelegate.needRefrsh = YES;
    [super btnBack];
}

@end
